package com.luyinbros.imagepicker;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.luyinbros.imagepicker.model.LocalMedia;
import com.luyinbros.imagepicker.model.LocalMediaFolder;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;


class FolderWindow extends PopupWindow {
    private Context context;
    private View window;
    private ViewGroup windowContainer;
    private RecyclerView recyclerView;
    private ImageFolderAdapter adapter;

    private boolean isDismiss = false;

    public FolderWindow(Context context) {
        this.context = context;
        window = LayoutInflater.from(context).inflate(R.layout.window_folder, null);
        this.setContentView(window);
        this.setWidth(getScreenWidth());
        this.setHeight(getScreenHeight() - dip2px(48));
        this.setAnimationStyle(R.style.WindowStyle);
        this.setFocusable(true);
        this.setOutsideTouchable(true);
        this.update();
        this.setBackgroundDrawable(new ColorDrawable(Color.argb(153, 0, 0, 0)));

        adapter = new ImageFolderAdapter(context);
        windowContainer = (ViewGroup) window.findViewById(R.id.window_container);
        windowContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        recyclerView = (RecyclerView) window.findViewById(R.id.folder_list);
        recyclerView.addItemDecoration(new ItemDivider());
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setAdapter(adapter);


    }


    public void bindFolder(List<LocalMediaFolder> folders) {
        adapter.bindFolder(folders);
    }

    public void show(View anchor) {
        super.showAtLocation(window, Gravity.BOTTOM, 0, dip2px(96));
        Animation animation = AnimationUtils.loadAnimation(context, R.anim.imagepicker_up_in);
        recyclerView.startAnimation(animation);
    }

    @Override
    public void showAsDropDown(View anchor) {
        super.showAsDropDown(anchor);

    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        adapter.setOnItemClickListener(onItemClickListener);
    }

    @Override
    public void dismiss() {
        if (isDismiss) {
            return;
        }
        isDismiss = true;
        Animation animation = AnimationUtils.loadAnimation(context, R.anim.imagepicker_down_out);
        recyclerView.startAnimation(animation);
        dismiss();
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                isDismiss = false;
                FolderWindow.super.dismiss();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    public LocalMediaFolder getSelectedFolder() {
        return adapter.folders.get(adapter.checkedIndex);
    }

    private class ItemDivider extends RecyclerView.ItemDecoration {
        private Paint mPaint;

        public ItemDivider() {
            mPaint = new Paint();
            mPaint.setColor(0xFFdcdcdc);

        }

        @Override
        public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
            final int left = dip2px(16);
            final int right = parent.getWidth() - left;

            final int childCount = parent.getChildCount();
            for (int i = 0; i < childCount - 1; i++) {
                final View child = parent.getChildAt(i);
                final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

                final int top = child.getBottom() + params.bottomMargin;
                final int bottom = top + 2;
                c.drawRect(left, top, right, bottom, mPaint);
            }
        }

    }

    private class ImageFolderAdapter extends RecyclerView.Adapter<ImageFolderAdapter.ViewHolder> {
        private Context context;
        private List<LocalMediaFolder> folders = new ArrayList<>();
        private int checkedIndex = -1;

        private OnItemClickListener onItemClickListener;

        public ImageFolderAdapter(Context context) {
            this.context = context;
        }

        public void bindFolder(List<LocalMediaFolder> folders) {
            this.folders = folders;
            checkedIndex = -1;
            if (folders != null && folders.size() > 0) {
                checkedIndex = 0;
            }
            notifyDataSetChanged();
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(context).inflate(R.layout.item_folder, parent, false);
            return new ViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, final int position) {
            final LocalMediaFolder folder = folders.get(position);
            if (folder != null) {
                String path = folder.getFirstImagePath();
                if (path == null) {
                    path = "";
                }
                Glide.with(context)
                        .load(new File(path))
                        .placeholder(R.drawable.ic_placeholder)
                        .error(R.drawable.ic_placeholder)
                        .centerCrop()
                        .into(holder.firstImage);
                holder.folderName.setText(folder.getName());
                holder.imageNum.setText(String.format("%1$s", folder.getImageNum()));

                holder.isSelected.setVisibility(checkedIndex == position ? View.VISIBLE : View.GONE);

                holder.contentView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (onItemClickListener != null) {
                            checkedIndex = position;
                            notifyDataSetChanged();
                            onItemClickListener.onItemClick(folder.getName(), folder.getImages());
                        }
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            return folders == null ? 0 : folders.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            ImageView firstImage;
            TextView folderName;
            TextView imageNum;
            ImageView isSelected;

            View contentView;

            public ViewHolder(View itemView) {
                super(itemView);
                contentView = itemView;
                firstImage = (ImageView) itemView.findViewById(R.id.first_image);
                folderName = (TextView) itemView.findViewById(R.id.folder_name);
                imageNum = (TextView) itemView.findViewById(R.id.image_num);
                isSelected = (ImageView) itemView.findViewById(R.id.is_selected);
            }
        }

        public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
            this.onItemClickListener = onItemClickListener;
        }

    }

    private int dip2px(float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    private int getScreenWidth() {
        DisplayMetrics localDisplayMetrics = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(localDisplayMetrics);
        return localDisplayMetrics.widthPixels;
    }

    private int getScreenHeight() {
        DisplayMetrics localDisplayMetrics = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(localDisplayMetrics);
        return localDisplayMetrics.heightPixels - getStatusBarHeight();
    }

    private int getStatusBarHeight() {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, statusBarHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return statusBarHeight;
    }

    public interface OnItemClickListener {
        void onItemClick(String folderName, List<LocalMedia> images);
    }
}
